package com.example.firstapp.network

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.example.firstapp.R
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class HttpURLConnectionActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_http_urlconnection)
        val url = URL(intent.getStringExtra("url"))
        println(url)
        thread {
            try {
                println(1)
                val response = StringBuilder()
                val connection = url.openConnection() as HttpURLConnection
                println(1)
                connection.requestMethod = "GET"
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                println(1)
                var input = connection.inputStream
                // 读取输入流
                val reader = BufferedReader(InputStreamReader(input))
                reader.use {
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                showResponse(response.toString())
            }catch (e:Exception){
            }
        }
    }
    private fun showResponse(res:String){
        runOnUiThread{
            val showResText:TextView = findViewById(R.id.showResText)
            showResText.text = res
        }
    }
}